package com.ktjiaoyu.server.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT 登录授权过滤器
 * @author jieGe
 **/
@Component
public class JwtAuthencationTokenFilter extends OncePerRequestFilter {

    @Value("${jwt.tokenHeader}") // 拿到的application.yml配置文件中jwt.tokenHeader 这个key所对应的值,值为Authorization
    private String tokenHeader;
    @Value("${jwt.tokenHead}") // 拿到的application.yml配置文件中jwt.tokenHead 这个key所对应的值,值为Bearer
    private String tokenHead;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 前端这边会发送请求到后端，如果是登录后其前端过来的请求其key为Authorization，另外value为"Bearer 空格JWT令牌"
        // 下面调用request.getHeader();得到本次请求头里key为Authorization所对应的值，值的格式为： "Bearer 空格JWT令牌"
        String authHeader = request.getHeader(tokenHeader);
        // 判断这个值里是否存在token
        if (null != authHeader && authHeader.startsWith(tokenHead)) {
            // 因为其值的格式为： "Bearer 空格JWT令牌"，通过substring将Bearer 后面的JWT令牌给截取出来
            String authToken = authHeader.substring(tokenHead.length()); 
            // tokenHead是上面的变量，其值在application.yml是Bearer
            // 根据获取请求中的token得到登录对象中的用户名
            String username = jwtTokenUtil.getUserNameFromToken(authToken);
            // token存在用户名但未登录
            if (null != username && null == SecurityContextHolder.getContext().getAuthentication()) {
                // 之前在AdminServiceImpl类中的login()方法里已经将生成的token字符串通过SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                //代码保存到了Spring Security全文中，这里从Spring Security全文中获取token进行非空判断，如果为空表示未登录
                // 调用UserDetailsService中的loadUserByUsername()进行登录
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                if (jwtTokenUtil.ValidateToken(authToken, userDetails)) { // 验证token是否有效
                    // 登录成功后将用户信息保存到UsernamePasswordAuthenticationToken中
                    UsernamePasswordAuthenticationToken authenticationToken =
                            new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    //authenticationToken设置到Spring Security全局上下文中。
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }
        // 放行
        filterChain.doFilter(request, response);
    }
}
